import update from "react-addons-update";

/**
 * list 模板
 * {
 *     key:必传，抽屉唯一id
 *     component:必传，抽屉显示组件
 *     modalProps:可空，抽屉api参数，参考https://ant.design/components/drawer-cn/
 *     comProps:可空，传递到子组件参数
 * }
 */
const ModalReducer: object = {
    namespace: "modalReducer",
    state: {
        list: []
    },
    createModal: function (modal: any) {
        // @ts-ignore
        const {list}: { list: object[] } = this.state;
        let curIndex: number = list.findIndex((item: any) => item.key === modal.key);

        let newList: any = update(list, {$push: [{...modal, open: true}]});

        if (curIndex !== -1) {
            newList = update(list, {$splice: [[curIndex, 1]]})
        }
        // @ts-ignore
        return update(this.state, {list: {$set: newList}})
    },
    updateModal: function (updateObj: any) {
        // @ts-ignore
        return this.updateModalOpt(updateObj.key, {...updateObj});
    },
    closeModal: function (updateObj: any) {
        // @ts-ignore
        return this.updateModalOpt(updateObj.key, {...updateObj, open: false});
    },
    updateModalOpt: function (key: string, updateObj: any = {}) {
        // @ts-ignore
        const {list}: { list: object[] } = this.state;
        let curIndex: number = list.findIndex((item: any) => item?.key === key);

        if (curIndex === -1) {
            // @ts-ignore
            return this.state;
        }

        let curNode: any = list[curIndex];

        let newList: object[] = update(list, {$splice: [[curIndex, 1, update(curNode, {$merge: updateObj})]]});

        // @ts-ignore
        return update(this.state, {list: {$set: newList}});
    },
    removeModal: function (key: string) {
        // @ts-ignore
        const {list}: { list: object[] } = this.state;

        let curIndex: number = list.findIndex((item: any) => item.key === key);
        let newList: object[] = update(list, {$splice: [[curIndex, 1]]});

        // @ts-ignore
        return update(this.state, {list: {$set: newList}})
    },
    removeAll: function () {
        // @ts-ignore
        return {
            ...this.state,
            list: []
        }
    },
};

export default ModalReducer;